package com.cn.lcc.base.Interceptor;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.util.IOUtils;
import com.cn.lcc.base.annotation.FieldCheck;
import com.cn.lcc.base.annotation.ParametersCheck;
import com.cn.lcc.base.exception.ParameterException;
import com.cn.lcc.util.request.RequestContextUtil;

/**
 * @author lcc
 * @date 2017年6月13日
 * @备注 所有参数解析放入requestContext
 */
public class RequestContextInterceptor extends HandlerInterceptorAdapter {
	private static final Logger logger = LoggerFactory
			.getLogger(RequestContextInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();
		ParametersCheck interceptor = method
				.getAnnotation(ParametersCheck.class);
		Map<String, String> params = new HashMap<String, String>();
		if (interceptor != null) {
			FieldCheck[] checks = interceptor.checks();
			// 可加额外验证
			for (FieldCheck check : checks) {
                params.put(check.name(), request.getParameter(check.name()));
			}
		}
		RequestContextUtil.setUri(request.getRequestURI());
		RequestContextUtil.setContext(params);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		RequestContextUtil.clear();
	}

	public static String getBodyString(BufferedReader br) {
		String inputLine;
		String str = "";
		try {
			while ((inputLine = br.readLine()) != null) {
				str += inputLine;
			}
			br.close();
		} catch (IOException e) {
			logger.info("IOException: " + e);
		}
		return str;
	}
}
